define(['template', 'utils', 'jquery'], (template) => {
	class Header{
		constructor () {
			this.loadHTML().then( () => {
				// promise成功后执行
				// 只要涉及header的一些DOM操作就都在这里写
				
				this.calcCartCount()
				this.loginName()
			})
		}
		
		loadHTML () {
			return new Promise( (resolve, reject) => {
				$('header').load('/html/modules/header.html', () => {
					resolve()
				})
			} )
		}
		
		getList () {
				  console.log("getList")
		  // ?id=356756867
		  const id = location.search.slice(4)
				
				console.log(id)
		  // $.get(`http://www.xiongmaoyouxuan.com/api/tab/${id}`, resp => {
			$.get(`http://www.xiongmaoyouxuan.com/api/tab/3`, resp => {
		    // console.log(resp)
		    if (resp.code === 200) {
		      const { list } = resp.data.items
		      const { cname } = resp.data.category
		      $('#hotGoodsUl').html(
		        template('hotGoodsUlTemplate', {
		          cname,
		          list
		        })
		      )
		    }
		  })
		}
		
		calcCartCount(){
			let count = 0
			let cart = localStorage.getItem('cart')
			if (cart) {
			  cart = JSON.parse(cart)
			  count = cart.reduce((num, shop) => {
			    num += shop.count
			    return num
			  }, 0)
			}
			$('#cartNum').html(count)
			// $('#cart span').html(count)
			if(count != 0){
				$('#buyCar .cart').remove()
			}
			
		}
		
		loginName(){
			
			// 验证cookie是否存在,判断登录状态
			var username = utils.getCookie('name')
			if (username) {
			  // 已登录
			  console.log(username)
			  $('#login')[0].className = 'hide'
			  $('#regist')[0].className = 'hide'
			  $('#username')[0].className = ''
			  $('#logout')[0].className = ''
			  $('#username')[0].innerHTML = "<a href='/html/login.html'>" + username + "</a>"
			}
			
			$('#logout')[0].addEventListener('click', function () {
			  if (confirm('确定要退出吗？')) {
			    // cookie清空
			    utils.setCookie('name', '', { expires: -1, path: '/' })
			    // 把ul显示隐藏切换一下
			    $('#login')[0].className = ''
			    $('#regist')[0].className = ''
				$('#username')[0].className = 'hide'
				$('#logout')[0].className = 'hide'
			  }
			})
			
			
			
		}
		
	}
	
	return new Header()
})